package com.example.uupaymuch.controller.channel.wudipay;

import com.example.uupaymuch.controller.notice.wudi.TransferComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@RestController
public class TransferController {

    @Autowired
    private TransferComponent transferComponent;

    private final Random random = new Random();
    private final double successProbability = 0.5; // 50% 的成功概率

    private static final Map<String, Object> PARAMS;

    // 静态初始化块
    static {
        PARAMS = new HashMap<>();
        PARAMS.put("addressing_key", "97592920093");
        PARAMS.put("addressing_key_type", "CPF");
        PARAMS.put("status", "CREATED");
        PARAMS.put("initialization_type", "DICT");
        PARAMS.put("fee", 0.03);
        PARAMS.put("account_id", 1);
        PARAMS.put("updated_at", "2023-12-04T18:34:52.000000Z");
        PARAMS.put("created_at", "2023-12-04T18:34:52.000000Z");
        PARAMS.put("id", 4);
    }

    @PostMapping("/api/cash-outs")
    public ResponseEntity<Map<String, Object>> getTestTransaction(@RequestBody Map<String, Object> request) {

        // 生成一个随机数，并与成功概率进行比较
        boolean isSuccess = random.nextDouble() < successProbability;
        Map<String, Object> response = PARAMS;
        // 模拟入参
        String key = request.get("key") != null ? (String) request.get("key") : "";
        String amount = request.get("amount") != null ? request.get("amount").toString() : "";
        String document_number = request.get("document_number") != null ? (String) request.get("document_number") : "";
        // 代付单号 T123456
        String correlation_id = request.get("correlation_id") != null ? (String) request.get("correlation_id") : "";
        String payStatus = request.get("payStatus") != null ? (String) request.get("payStatus") : "3"; // 正常回调按照成功

        String payStatusStr = "";
        response.put("uuid", key);
        response.put("amount", amount);
        response.put("correlation_id", correlation_id);
        if (StringUtils.isNotEmpty(payStatus)) {
            switch (payStatus) {
                case "3":
                    payStatusStr = "DONE";
                    break;
                case "4":
                    payStatusStr = "FAILED";
                    break;
                default:
                    payStatusStr = "DONE";
                    break;
            }
        }
//        payStatusStr = isSuccess ? "DONE" : "FAILED";
        // 回调
        transferComponent.doNotifyTransfer(correlation_id, payStatusStr, amount);

        return ResponseEntity.ok(response);
    }
}